package org.pjsip.pjsua2.app;

/* $Id: MainActivity.java 5022 2015-03-25 03:41:21Z nanang $ */
/*
 * Copyright (C) 2013 Teluu Inc. (http://www.teluu.com)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

import android.os.Bundle;
import android.app.Activity;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.gwf.llsipproject.R;
import com.gwf.llsipproject.Utils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;

import org.pjsip.bean.SipResponse;
import org.pjsip.constant.SipStatus;
import org.pjsip.iface.OnSipStatusChangedListener;
import org.pjsip.iface.OnSipStatusChangedListenerImpl;
import org.pjsip.manager.SipManager;
import org.pjsip.pjsua2.*;
import org.pjsip.utils.LocalStorageUtils;

public class MainActivity extends Activity implements OnSipStatusChangedListener {
    private static final String TAG = "MainActivity";

    private EditText et3, et4, et9;

    private TextView tvStatus1, tvStatus2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //TODO 必须手动打开悬浮窗权限

        MySipPhoneEvent.setOnSipStatusChangedListener(this);

        AndPermission.with(this)
                .runtime()
                .permission(Permission.RECORD_AUDIO,
                        Permission.READ_PHONE_STATE,
                        Permission.READ_CALL_LOG,
                        Permission.CAMERA,
                        Permission.CALL_PHONE)
                .onGranted(permissions -> {
                })
                .onDenied(permissions -> {
                })
                .start();

        et3 = findViewById(R.id.et_3);
        et4 = findViewById(R.id.et_4);
        et9 = findViewById(R.id.et_9);

        tvStatus1 = findViewById(R.id.tv_status1);
        tvStatus2 = findViewById(R.id.tv_status2);
        Button btn1 = findViewById(R.id.btn_1);
        Button btn2 = findViewById(R.id.btn_2);
        Button btn3 = findViewById(R.id.btn_3);
        Button btn4 = findViewById(R.id.btn_4);

        /**
         * 注册
         */
        btn1.setOnClickListener(v -> {
            String userName = et3.getText().toString();
            String pwd = et4.getText().toString();
            if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(pwd)) {
                Toast.makeText(MainActivity.this, "输入用户名或密码", Toast.LENGTH_SHORT).show();
                return;
            }
            MyApplication.getInstance().setUserName(userName);
            MyApplication.getInstance().setPwd(pwd);
            SipManager.getInstance().registerSip(userName, pwd);
        });
        /**
         * 注销
         */
        btn2.setOnClickListener(v -> SipManager.getInstance().unregisterSip());
        /**
         * 外呼
         */
        btn3.setOnClickListener(v -> {
            String phone = et9.getText().toString();
            if (StringUtils.isEmpty(phone)) {
                Toast.makeText(MainActivity.this, "号码不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            MyApplication.getInstance().setPhone(phone);
            SipManager.getInstance().makeCall(phone);
        });
        /**
         * 挂断
         */
        btn4.setOnClickListener(v -> SipManager.getInstance().dropCall());
    }


    private void reMakeCall() {
        MyApplication mApp = MyApplication.getInstance();
        String phone = mApp.getPhone();
        if (StringUtils.isEmpty(phone)) {
            return;
        }
        SipManager.getInstance().makeCall(phone);
    }

    @Override
    public void onSipStatusChanged(SipResponse sipResponse) {
        // Log.d(TAG, "onSipStatusChanged: ------->"+ GsonUtils.toJson(sipResponse));

        if (sipResponse != null) {
            try {
                String type = sipResponse.getType();
                int code = sipResponse.getCode();
                String msg = sipResponse.getMsg();
                Log.d(TAG, "onSipStatusChanged: --------->" + type + "----->" + code);
                if (StringUtils.equals("init", type)) {
                    tvStatus1.setText(code == 1 ? "已签入" : "未签入");
                    if (code == -1) {
                        LogUtils.e("onSipStatusChanged: init 参数错误:" + msg);
                    }
                } else if (StringUtils.equals("login", type)) {
                    if (code == 1) {
                        Log.d(TAG, "onSipStatusChanged: ---->已签入");
                    } else if (code == 0) {
                        SipManager.getInstance().login();
                        Log.d(TAG, "onSipStatusChanged: ---->签入失败，重新签入");
                    } else if (code == -999) {
                        //code=-999, 是签入请求的第一个状态码，勿在此使用login方法，否则死循环签入
                        Log.d(TAG, "onSipStatusChanged: -999--->" + msg);
                    } else if (code == -1) {
                        //其他错误，不需要再尝试登陆
                        Log.d(TAG, "onSipStatusChanged: -1--->" + msg);
                    } else if (code == -99) {
                        //Json解析错误
                        Log.d(TAG, "onSipStatusChanged: -99--->" + msg);
                    } else if (code == -100) {
                        Log.d(TAG, "onSipStatusChanged: -100----uninit completed");
                        SipManager.getInstance().unregisterSip();
                    } else if (code == -200) {
                        Log.d(TAG, "onSipStatusChanged: -200----注销 completed");
                        SipManager.getInstance().releaseRes();
                    }
                } else if (StringUtils.equals("http", type)) {
                    if (code == -99) {
                        //网络错误
                        Log.d(TAG, "onSipStatusChanged: -99--->网络错误" + msg);
                    }
                } else if (StringUtils.equals("call_status", type)) {

                    if (code == -66) {
                        Log.d(TAG, "onSipStatusChanged: ---->终端异常，需重新初始化，再呼叫");
                        SipManager.getInstance().registerSip(MyApplication.getInstance().getUserName(), MyApplication.getInstance().getPwd());
                        reMakeCall();
                    } else if (code == -88) {
                        Log.d(TAG, "onSipStatusChanged: ---->分机状态错误，需尝试登陆(login即可)，再呼叫");
                        SipManager.getInstance().login();
                        new Handler().postDelayed(this::reMakeCall, 1000);
                    } else if (code == -99) {
                        Log.d(TAG, "onSipStatusChanged: ---->Json解析错误（系统内部错误）");
                    } else if (code == -1) {
                        Log.d(TAG, "onSipStatusChanged: ---->其他错误，请联系管理员排查再使用");
                        Log.d(TAG, "onSipStatusChanged: --" + msg);
                    } else if (code == 7) {
                        Log.d(TAG, "onSipStatusChanged: ------发送按键成功");
                    } else if (code == 8) {
                        Log.d(TAG, "onSipStatusChanged: ------发送按键失败");
                    } else {
                        if (code == 1) {
                            SipManager.getInstance().resetLoginCnt();
                        }
                        tvStatus2.setText(SipStatus.getValueByKey(code));


                        //TODO 进入通话流程  详细状态请参考 SipStatus

                        // DialWindow.getInstance().showDialWindowByStatus(code);
                    }
                }
            } catch (Exception e) {
                Log.e("onSipStatusChanged:", e.toString());
            }
        }
    }
}
